import router from './router'
import { getToken, } from './utils/token';
import { isHttp, isPathMatch } from '@/utils/validate';
import { isRelogin } from './utils/request';
import useUserStore from '@/stores/modules/user';
import usePermissionStore from '@/stores/modules/permission';
import { ElNotification } from "element-plus";
//顶部进度条
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
let i = 0;
//关闭loading
NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register'];

const isWhiteList = (path) => {
  // return whiteList.some(pattern => isPathMatch(pattern, path))
  return whiteList.some(item => path == item);
}
router.beforeEach((to, from, next) => {
  NProgress.start();

  if (getToken()) {
    if(to.meta.title){
      document.title = to.meta.title;
    }
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done();
    } else if (isWhiteList(to.path)) {
      next()
    } else {
      //权限验证 信息
      if (!useUserStore().role) {
        //true情况下不进入401code
        isRelogin.show = true;
        //获取用户信息
        useUserStore().getInfo().then(res => {
          isRelogin.show = false;
          usePermissionStore().generateRoutes().then(res=>{
            res.forEach(route=>{
              if (!isHttp(route.path)) {
                router.addRoute(route) // 动态添加可访问路由表
              }
            })
            next({ path:to.path, replace: true });
          })
        }).catch(err=>{
          useUserStore().logOut().then(() => {
            ElNotification({
              title: "账号已退出，回到登录页",
              type: "success",
            });
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {

    if (isWhiteList(to.path)) {

      next();
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }  // 显式编码参数
      });
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
